package io.jpress.addon.servicebulletins.directive;

import com.jfinal.aop.Inject;
import com.jfinal.core.Controller;
import com.jfinal.core.JFinal;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;
import com.jfinal.template.Env;
import com.jfinal.template.io.Writer;
import com.jfinal.template.stat.Scope;
import io.jboot.db.model.Columns;
import io.jboot.web.controller.JbootControllerContext;
import io.jboot.web.directive.annotation.JFinalDirective;
import io.jboot.web.directive.base.JbootDirectiveBase;
import io.jboot.web.directive.base.PaginateDirectiveBase;
import io.jpress.JPressConsts;
import io.jpress.JPressOptions;
import io.jpress.addon.servicebulletins.model.JpressAddonServicebulletins;
import io.jpress.addon.servicebulletins.service.JpressAddonServicebulletinsService;
import io.jpress.commons.directive.DirectveKit;
import io.jpress.model.User;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;


@JFinalDirective("ServiceBulletinsList")
public class ServiceBulletinsDirective extends JbootDirectiveBase {

    @Inject
    private JpressAddonServicebulletinsService service;

    @Override
    public void onRender(Env env, Scope scope, Writer writer) {

        Controller controller = JbootControllerContext.get();
        int page = controller.getParaToInt(1, 1);
        Integer pageSize = getParaToInt("pageSize", scope,10);
        User attr = controller.getAttr(JPressConsts.ATTR_LOGINED_USER);
        Long userid = attr.getId();

//        Columns columns = Columns.create();

        String keyword = controller.getPara("keyword");
        String model = controller.getPara("model");
        if(model==null)
            model = getPara("model", scope);


        String circularnumber = controller.getPara("circularnumber");
        String startTime = controller.getPara("startTime");
        String endTime = controller.getPara("endTime");

//        if(keyword!=null && !keyword.equals("")){
//            columns.like("title", "%"+keyword+"%").or().like("title_en", "%"+keyword+"%");
//        }
//        columns.eq("model",model).eq("circular_number",circularnumber)
//                .ge("release_date",strtodata(startTime))
//                .le("release_date",strtodata(endTime));

        SqlPara sqlPara = new SqlPara();

        String sql =  "SELECT a.* FROM addon_servicebulletins a LEFT JOIN addon_servicebulletins_user b on b.servicebulletins_id = a.id WHERE user_id = "+userid;
        if(keyword!=null) {
            sql += " and (title like ? or title_en like ?)";
            sqlPara.addPara("%"+keyword+"%");
            sqlPara.addPara("%"+keyword+"%");
        }
        if(circularnumber!=null) {
            sql += " and circular_number = ?";
            sqlPara.addPara(circularnumber);
        }
        if(model!=null) {
            sql += " and model = ?";
            sqlPara.addPara(model);
        }
        if(startTime!=null) {
            sql += " and release_date >= to_date(?,'yyyy-MM-dd')";
            sqlPara.addPara(startTime);
        }
        if(endTime!=null){
            sql += " and release_date <= to_date(?,'yyyy-MM-dd')";
            sqlPara.addPara(endTime);
        }

        sqlPara.setSql(sql+" order by release_date desc");

        Page<Record> paginate = Db.paginate(page, pageSize, sqlPara);

        scope.setLocal("ServiceBulletinsList",paginate);
        renderBody(env, scope, writer);
    }

    private Date strtodata(String str){

        if (str==null || str.trim().equals("")) return null;

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date time = null;
        try {
            time = sdf.parse(str);
        } catch (ParseException e) {
            System.out.println("时间格式不正确");
        }

        return time;
    }

    @JFinalDirective("ServiceBulletinsPaginate")
    public static class TemplatePaginateDirective extends PaginateDirectiveBase {

        @Override
        protected String getUrl(int pageNumber, Env env, Scope scope, Writer writer) {
            HttpServletRequest request = JbootControllerContext.get().getRequest();
            String url = request.getRequestURI();
            String contextPath = JFinal.me().getContextPath();

            boolean firstGotoIndex = getPara("firstGotoIndex", scope, false);

            if (pageNumber == 1 && firstGotoIndex) {
                return contextPath + "/";
            }

            // 如果当前页面是首页的话
            // 需要改变url的值，因为 上一页或下一页是通过当前的url解析出来的
            if (url.equals(contextPath + "/")) {
                url = contextPath + "/servicebulletins/index"
                        + JPressOptions.getAppUrlSuffix();
            }
            return DirectveKit.replacePageNumber(url, pageNumber);
        }

        @Override
        protected Page<?> getPage(Env env, Scope scope, Writer writer) {
            return (Page<?>) scope.get("ServiceBulletinsList");
        }

    }


    @Override
    public boolean hasEnd() {
        return true;
    }
}
